package com.sgb.kjwl.view.ui.activity.self.driver;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AppNewProprietaryDriverActivityBinding;
import com.sgb.kjwl.model.entity.self.LicenceOCREntity;
import com.sgb.kjwl.model.entity.self.MotorcadeSimpleEntity;
import com.sgb.kjwl.model.entity.self.ProDriverRegisterEntity;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.kjwl.utils.ImageUtil;
import com.sgb.kjwl.utils.PickerHelper;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.swgk.core.event.MenuEvent;
import com.sgb.kjwl.view.ui.activity.self.CameraActivity;
import com.sgb.kjwl.view.ui.activity.transport.company.AddProprietaryFleetActivity;
import com.sgb.kjwl.view.widget.ChoosePictureDialog;
import com.sgb.kjwl.view.widget.SimpleCountDownTimer;
import com.sgb.kjwl.viewmodel.self.driver.NewProDriverModel;
import com.sgb.link.router.PathDriver;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.sgb.link.router.PathDriver.NewProprietaryDriverActivity;

/**
 * Describe:    新增自营司机
 * Author:  yangLei
 * Date:    2021/10/12
 */
@Route(path = NewProprietaryDriverActivity)
public class NewProprietaryDriverActivity extends BaseActivity<NewProDriverModel, AppNewProprietaryDriverActivityBinding> {
    @Autowired(name = RouterKey.STRING, desc = "需要注册的司机的手机号")
    public String phoneNum;

    private ProDriverRegisterEntity registerEntity;
    private ChoosePictureDialog mChoosePictureDialog;//选择照片
    private OptionsPickerView<MotorcadeSimpleEntity> motorcadePicker;//车队选择器
    private List<MotorcadeSimpleEntity> motorcades = new ArrayList<>();

    /**
     * 照片类型
     */
    private int type;
    public final int LICENSE_MAIN = 1;   //驾驶照正页
    public final int LICENSE_DEPUTY = 2;  //驾驶证副页

    @Override
    protected int layoutId() {
        return R.layout.app_new_proprietary_driver_activity;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(NewProDriverModel.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        SoftInputKeepOutUtils.assistActivity(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //每次界面可见请求最新的车队信息数据
        mViewModel.requestMotorcadeList();
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        initViews();
        initEvents();
        initData();
    }

    private void initData() {
        if (TextUtils.isEmpty(phoneNum)) {
            showToast("手机号为空");
            finish();
        } else {
            registerEntity = new ProDriverRegisterEntity();
            registerEntity.setTelPhone(phoneNum);
            mViewModel.getLocation(this);
        }
    }

    private void initViews() {
        mBinding.includeTitle.titleView.setText("新增自营司机");
        mBinding.phoneNumber.setText(!TextUtils.isEmpty(phoneNum) ? phoneNum : "");

        if (UserOperating.getInstance().isTeam()) {
            mBinding.chooseMotorcadeLine.setVisibility(View.GONE);
            mBinding.chooseMotorcadeLay.setVisibility(View.GONE);
        } else if (UserOperating.getInstance().isCompany()) {
            mBinding.chooseMotorcadeLine.setVisibility(View.VISIBLE);
            mBinding.chooseMotorcadeLay.setVisibility(View.VISIBLE);
        }
    }

    private void initEvents() {
        mBinding.setOnClick(this);
        mBinding.includeTitle.ivBack.setOnClickListener(v -> finish());
        mViewModel.motorcadeListLD.observe(this, list -> {
            handleMotorcadeListRequest(list);
        });
        mViewModel.registerLD.observe(this, no -> {
            if (!TextUtils.isEmpty(no)) {
                if (no.equals("400")) {
                    showRealNameIsDifferentWithOCRInfo();
                } else {
                    showToast("注册成功");
                    EventBus.getDefault().postSticky(MenuEvent.make(EventConstant.EVENT_REFRESH_PRO_DRIVER, null));
                    ARouter.getInstance().build(PathDriver.ProprietaryDriverDetailsActivity)
                            .withString(RouterKey.ID, no)
                            .navigation(NewProprietaryDriverActivity.this);
                    finish();
                }
            } else {
                showToast("注册失败");
            }
        });
        mViewModel.codeLD.observe(this, aBoolean -> {
            if (aBoolean != null && aBoolean) {
                showToast("操作成功");
                starCountdown();
            }
        });
        mViewModel.OCRLD.observe(this, licenceOCREntity -> handleOcrResult(licenceOCREntity));
    }

    /**
     * 车队请求结果处理
     *
     * @param list
     */
    @SuppressLint("ResourceAsColor")
    private void handleMotorcadeListRequest(List<MotorcadeSimpleEntity> list) {
        motorcades.clear();
        if (list == null || list.size() <= 0) {
            mBinding.belongsTeam.setText("去添加车队");
            mBinding.belongsTeam.setTextColor(R.color.color_5792FD);
            registerEntity.setMotorcadeNo("");
            registerEntity.setMotorcadeName("");
        } else {
            motorcades.addAll(list);
            if (mBinding.belongsTeam.getText().toString() != null && mBinding.belongsTeam.getText().toString().equals("去添加车队")) {
                mBinding.belongsTeam.setText("");
                mBinding.belongsTeam.setTextColor(R.color.black);
            }
        }
    }

    /**
     * 获取验证码倒计时
     */
    public void starCountdown() {
        SimpleCountDownTimer mCountDownTimerUtils = new SimpleCountDownTimer(NewProprietaryDriverActivity.this, mBinding.obtainCode,
                60000, 1000, false); //倒计时1分钟
        mCountDownTimerUtils.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.belongs_team:
                //企业下面有无车队判断
                //1.有车队去选择
                if (motorcades.size() > 0) {
                    hideKeyboard();
                    motorcadeListRequestResult(motorcades);
                }
                //2.无车队去添加
                else {
                    AddProprietaryFleetActivity.start(this, true);
                }
                break;

            case R.id.obtain_code:
                mViewModel.getCode(phoneNum);
                break;

            case R.id.delete_main_pic:
                registerEntity.setMainDriverLicense("");
                mBinding.drivingLicenceMain.setImageDrawable(getResources().getDrawable(R.drawable.img_license_main));
                mBinding.deleteMainPic.setVisibility(View.GONE);
                break;
            case R.id.delete_deputy_pic:
                registerEntity.setViceDriverLicense("");
                mBinding.drivingLicenceDeputy.setImageDrawable(getResources().getDrawable(R.drawable.img_license_deputy));
                mBinding.deleteDeputyPic.setVisibility(View.GONE);
                break;

            case R.id.submit_btn:
                if (checkInputInfo()) {
                    mViewModel.uploadDataRegisterDriver(this, registerEntity);
                }
                break;

            case R.id.driving_licence_main:
                mChoosePictureDialog = new ChoosePictureDialog(this, R.drawable.img_license_main_no_camera);
                mChoosePictureDialog.setDialogClickCallBack(new ChoosePictureDialog.DialogClickCallBack() {
                    @Override
                    public void onItemClick(String ids) {
                        if (ids.equals("拍照")) {
                            startCamera(LICENSE_MAIN);
                        } else if (ids.equals("从手机相册选择")) {
                            getImageByAlbum(LICENSE_MAIN);
                        }
                    }
                });
                mChoosePictureDialog.show(getSupportFragmentManager(), "1");
                break;

            case R.id.driving_licence_deputy:
                mChoosePictureDialog = new ChoosePictureDialog(this, R.drawable.img_license_deputy_no_camera);
                mChoosePictureDialog.setDialogClickCallBack(new ChoosePictureDialog.DialogClickCallBack() {
                    @Override
                    public void onItemClick(String ids) {
                        if (ids.equals("拍照")) {
                            startCamera(LICENSE_DEPUTY);
                        } else if (ids.equals("从手机相册选择")) {
                            getImageByAlbum(LICENSE_DEPUTY);
                        }
                    }
                });
                mChoosePictureDialog.show(getSupportFragmentManager(), "2");
                break;
        }
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     */
    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        // 隐藏软键盘
        imm.hideSoftInputFromWindow(this.getWindow().getDecorView().getWindowToken(), 0);
    }

    /**
     * 检查输入信息是否为空
     *
     * @return
     */
    private boolean checkInputInfo() {
        if (!TextUtils.isEmpty(mBinding.driverName.getText().toString().trim())) {
            registerEntity.setRealName(mBinding.driverName.getText().toString().trim());
        } else {
            showToast("请输入司机姓名");
            registerEntity.setRealName("");
            mBinding.driverName.requestFocus();
            return false;
        }

        if (!TextUtils.isEmpty(mBinding.idCardNumber.getText().toString().trim())) {
            registerEntity.setIdentityCard(mBinding.idCardNumber.getText().toString().trim());
        } else {
            showToast("请输入身份证号");
            registerEntity.setIdentityCard("");
            mBinding.idCardNumber.requestFocus();
            return false;
        }

        if (!TextUtils.isEmpty(mBinding.verifyCode.getText().toString().trim())) {
            registerEntity.setCode(mBinding.verifyCode.getText().toString().trim());
        } else {
            showToast("请输入验证码");
            registerEntity.setCode("");
            mBinding.verifyCode.requestFocus();
            return false;
        }

        if (TextUtils.isEmpty(registerEntity.getMainDriverLicense())) {
            showToast("请先上传驾驶证主页");
            return false;
        }

        if (TextUtils.isEmpty(registerEntity.getViceDriverLicense())) {
            showToast("请先上传驾驶证副页");
            return false;
        }

        if (!TextUtils.isEmpty(mBinding.name.getText().toString().trim())) {
            registerEntity.setName(mBinding.name.getText().toString().trim());
        } else {
            showToast("请先输入姓名");
            registerEntity.setName("");
            mBinding.name.requestFocus();
            return false;
        }

        if (!TextUtils.isEmpty(mBinding.licenceNumber.getText().toString().trim())) {
            registerEntity.setIdCard(mBinding.licenceNumber.getText().toString().trim());
        } else {
            showToast("请先输入驾驶证证号");
            registerEntity.setIdCard("");
            mBinding.licenceNumber.requestFocus();
            return false;
        }
        if (!TextUtils.isEmpty(mBinding.archivesNumber.getText().toString().trim())) {
            registerEntity.setFileNumber(mBinding.archivesNumber.getText().toString().trim());
        } else {
            showToast("请先输入档案编号");
            registerEntity.setFileNumber("");
            mBinding.archivesNumber.requestFocus();
            return false;
        }
        return true;
    }

    /**
     * 请求自营车队结果
     *
     * @param list
     */
    @SuppressLint("ResourceAsColor")
    private void motorcadeListRequestResult(List<MotorcadeSimpleEntity> list) {
        if (motorcadePicker == null)
            motorcadePicker = PickerHelper.with(this).getCommonPicker("选择所属车队", list, (options1, options2, options3, v) -> {
                if (list.size() > options1) {
                    MotorcadeSimpleEntity entity = list.get(options1);
                    registerEntity.setMotorcadeName(entity.getMotorcadeName());
                    registerEntity.setMotorcadeNo(entity.getMotorcadeNo());
                    mBinding.belongsTeam.setText(!TextUtils.isEmpty(entity.getMotorcadeName()) ? entity.getMotorcadeName() : "");
                    mBinding.belongsTeam.setTextColor(R.color.black);
                }
            });
        motorcadePicker.show();
    }

    public void showToast(String text) {
        MToast.showToast(getApplicationContext(), text);
    }

    /**
     * 调用相机拍照
     *
     * @param type
     */
    private void startCamera(int type) {
        this.type = type;
        if (this.type == LICENSE_MAIN) {
            CameraActivity.start(this, 0, "驾驶证主页", PictureConfig.REQUEST_CAMERA);
        } else {
            CameraActivity.start(this, 1, "驾驶证副页", PictureConfig.REQUEST_CAMERA);
        }
    }

    /**
     * 从相册获取图片
     *
     * @param type
     */
    private void getImageByAlbum(int type) {
        this.type = type;
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .selectionMode(PictureConfig.SINGLE)
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .compress(true)//是否压缩
                .minimumCompressSize(2 * 1024)//小于2M不压缩
                .maxSelectNum(1)//能选多少张图片
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    File file = new File(selectList.get(0).getRealPath());
                    MLog.d("图片路径：", selectList.get(0).getRealPath());
                    if (file.exists()) {
                        MLog.d("图片", "存在");
                    }
                    if (LICENSE_MAIN == type) {
                        Glide.with(this).load(file).into(mBinding.drivingLicenceMain);
                        mBinding.deleteMainPic.setVisibility(View.VISIBLE);
                        mViewModel.uploadMutFileModel(this, ImageUtil.getImage(selectList.get(0).getRealPath()), LICENSE_MAIN);
                    } else if (type == LICENSE_DEPUTY) {
                        //Bugly报file为空
                        if (file.length() > 0) {
                            Glide.with(this).load(file).into(mBinding.drivingLicenceDeputy);
                            mBinding.deleteDeputyPic.setVisibility(View.VISIBLE);
                        }
                        if (!TextUtils.isEmpty(selectList.get(0).getRealPath())) {
                            mViewModel.uploadMutFileModel(this, ImageUtil.getImage(selectList.get(0).getRealPath()), LICENSE_DEPUTY);
                        }
                    }
                    break;
                case PictureConfig.REQUEST_CAMERA:
                    String path = data.getStringExtra("imagePath");
                    File takePictureFile = new File(path);
                    if (LICENSE_MAIN == type) {
                        Glide.with(this).load(takePictureFile).into(mBinding.drivingLicenceMain);
                        mViewModel.uploadMutFileModel(this, ImageUtil.getImage(path), LICENSE_MAIN);
                    } else if (type == LICENSE_DEPUTY) {
                        //Bugly报file为空
                        if (takePictureFile.length() > 0) {
                            Glide.with(this).load(takePictureFile).into(mBinding.drivingLicenceDeputy);
                        }
                        if (!TextUtils.isEmpty(path)) {
                            mViewModel.uploadMutFileModel(this, ImageUtil.getImage(path), LICENSE_DEPUTY);
                        }
                    }
            }
        }
    }

    /**
     * 上传图片成功
     *
     * @param urls
     * @param type
     */
    public void uploadImgSuccess(String urls, int type) {
        if (type == LICENSE_MAIN) {
            registerEntity.setMainDriverLicense(urls);
        } else if (type == LICENSE_DEPUTY) {
            registerEntity.setViceDriverLicense(urls);
        }
        getOCRLicenceInfo();
    }

    /**
     * 主页和副业都上传成功，则调用OCR识别接口
     */
    private void getOCRLicenceInfo() {
        if (!TextUtils.isEmpty(registerEntity.getMainDriverLicense()) && !TextUtils.isEmpty(registerEntity.getViceDriverLicense())) {
            mViewModel.getOCRLicenceInfo(this, registerEntity.getMainDriverLicense(), registerEntity.getViceDriverLicense());
        }
    }

    /**
     * 处理OCR识别结果
     *
     * @param ocrEntity
     */
    private void handleOcrResult(LicenceOCREntity ocrEntity) {
        if (ocrEntity == null) {
            oCRFail();
        } else {
            oCRSuccess(ocrEntity);
        }
    }

    /**
     * OCR识别失败提示
     */
    public void oCRFail() {
        new RoundDialog.Builder(this)
                .title("提示")
                .content("证照无法识别，可重新上传或填写后提交人工审核")
                .singleBtn(true)
                .confirm("确定")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .show();
        registerEntity.setImageName("");
        registerEntity.setImageIdCard("");
        registerEntity.setImageFileNumber("");
        registerEntity.setImageQuasiDrivingModels("");
        registerEntity.setImageDriverSLicenseAuthority("");
        registerEntity.setImageValidityPeriodStart("");
        registerEntity.setImageValidityPeriodEnd("");
        setTextInfo("", "", "");
    }

    /**
     * OCR识别成功
     */
    public void oCRSuccess(LicenceOCREntity licenceOCREntity) {
        //每次调用OCR识别后第一次提交如果与实名信息不同的时候，都需要提示用户与实名信息不符
        registerEntity.setManualCheck(false);
        registerEntity.setImageName(licenceOCREntity.getImageName());
        registerEntity.setImageIdCard(licenceOCREntity.getImageIdCard());
        registerEntity.setImageFileNumber(licenceOCREntity.getImageFileNumber());
        registerEntity.setImageQuasiDrivingModels(licenceOCREntity.getImageQuasiDrivingModels());
        registerEntity.setImageDriverSLicenseAuthority(licenceOCREntity.getImageDriverSLicenseAuthority());
        registerEntity.setImageValidityPeriodStart(licenceOCREntity.getImageValidityPeriodStart());
        registerEntity.setImageValidityPeriodEnd(licenceOCREntity.getImageValidityPeriodEnd());
        setTextInfo(licenceOCREntity.getImageName(), licenceOCREntity.getImageIdCard(), licenceOCREntity.getImageFileNumber());
    }

    /**
     * 实名信息于OCR识别的信息不符
     * 点击“提交”按钮，可以强制提交人工审核
     */
    public void showRealNameIsDifferentWithOCRInfo() {
        new RoundDialog.Builder(this)
                .title("提示")
                .content("驾驶证信息与实名认证信息不一致，继续提交后将由工作人员审核，是否继续提交？")
                .cancel("提交")
                .confirm("暂不提交")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .cancelCallback(v -> {
                    registerEntity.setManualCheck(true);
                    if (checkInputInfo()) {
                        mViewModel.uploadDataRegisterDriver(this, registerEntity);
                    }
                }).show();
    }

    /**
     * 设置驾驶证识别信息
     *
     * @param imageName       姓名
     * @param imageIdCard     身份证号
     * @param imageFileNumber 档案编号
     */
    private void setTextInfo(String imageName, String imageIdCard, String imageFileNumber) {
        mBinding.licenseInfoLayout.setVisibility(View.VISIBLE);
        mBinding.tipsText.setVisibility(View.VISIBLE);
        mBinding.name.setText(imageName);
        mBinding.licenceNumber.setText(imageIdCard);
        mBinding.archivesNumber.setText(imageFileNumber);
    }

}
